<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Golang GORM使用 | J.のblog</title><meta name="keywords" content="云原生,golang"><meta name="author" content="J."><meta name="copyright" content="J."><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="description" content="GORMSQLBuilderSQLBuilder是一个用于生成SQL语句的库。 项目地址：  https:&#x2F;&#x2F;gitee.com&#x2F;iRainIoT&#x2F;go-sqlbuilder、https:&#x2F;&#x2F;github.com&#x2F;parkingwang&#x2F;go-sqlbuilder 目前已支持MySQL基本Select&#x2F;Update&#x2F;Insert&#x2F;Delete&#x2F;Where 等">
<meta property="og:type" content="article">
<meta property="og:title" content="Golang GORM使用">
<meta property="og:url" content="http://dycloudnavite.love/2023/05/06/Golang%E4%B8%AD%E7%9A%84GORM/index.html">
<meta property="og:site_name" content="J.のblog">
<meta property="og:description" content="GORMSQLBuilderSQLBuilder是一个用于生成SQL语句的库。 项目地址：  https:&#x2F;&#x2F;gitee.com&#x2F;iRainIoT&#x2F;go-sqlbuilder、https:&#x2F;&#x2F;github.com&#x2F;parkingwang&#x2F;go-sqlbuilder 目前已支持MySQL基本Select&#x2F;Update&#x2F;Insert&#x2F;Delete&#x2F;Where 等">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://dycloudnavite.love/img/golang.png">
<meta property="article:published_time" content="2023-05-06T06:32:00.000Z">
<meta property="article:modified_time" content="2023-08-30T03:01:51.741Z">
<meta property="article:author" content="J.">
<meta property="article:tag" content="云原生">
<meta property="article:tag" content="golang">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://dycloudnavite.love/img/golang.png"><link rel="shortcut icon" href="/dujie5416/img/touxiang.png"><link rel="canonical" href="http://dycloudnavite.love/2023/05/06/Golang%E4%B8%AD%E7%9A%84GORM/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/dujie5416/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/dujie5416/',
  algolia: {"appId":"9GWB2VV7GN","apiKey":"dac56ec5b0b1f45281251ee59db4d637","indexName":"blog","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Golang GORM使用',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-08-30 11:01:51'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/xxx.css"><link rel="stylesheet" href="/css/universe.css"><link rel="stylesheet" href="/css/custom.css"><style type="text/css">#toggle-sidebar {bottom: 80px}</style><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/tzy13755126023/BLOG_SOURCE/css/function.min.css"><link rel="stylesheet" href="/css/rightMenu.css"><style type="text/css">#toggle-sidebar {left:100px}</style><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.css" /><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.2.0"><link rel="alternate" href="/dujie5416/atom.xml" title="J.のblog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/dujie5416/img/touxiang.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/dujie5416/img/longzhu.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/dujie5416/">J.のblog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Golang GORM使用</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-05-06T06:32:00.000Z" title="发表于 2023-05-06 14:32:00">2023-05-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-08-30T03:01:51.741Z" title="更新于 2023-08-30 11:01:51">2023-08-30</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/dujie5416/categories/golang/">golang</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Golang GORM使用"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="GORM"><a href="#GORM" class="headerlink" title="GORM"></a>GORM</h1><h3 id="SQLBuilder"><a href="#SQLBuilder" class="headerlink" title="SQLBuilder"></a>SQLBuilder</h3><p>SQLBuilder是一个用于生成SQL语句的库。</p>
<p>项目地址：</p>
<ul>
<li><a target="_blank" rel="noopener" href="https://gitee.com/iRainIoT/go-sqlbuilder%E3%80%81https://github.com/parkingwang/go-sqlbuilder">https://gitee.com/iRainIoT/go-sqlbuilder、https://github.com/parkingwang/go-sqlbuilder</a><ul>
<li>目前已支持MySQL基本Select&#x2F;Update&#x2F;Insert&#x2F;Delete&#x2F;Where 等语法</li>
<li>目前只支持MySQL语法</li>
<li>未支持多表查询</li>
<li><code> go get -u github.com/parkingwang/go-sqlbuilder</code></li>
</ul>
</li>
<li><a target="_blank" rel="noopener" href="https://github.com/huandu/go-sqlbuilder">https://github.com/huandu/go-sqlbuilder</a>，功能更强<ul>
<li><code>go get github.com/huandu/go-sqlbuilder </code></li>
</ul>
</li>
</ul>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main
<span class="token keyword">import</span> <span class="token punctuation">(</span>
 <span class="token string">"database/sql"</span>
 <span class="token string">"fmt"</span>
 <span class="token string">"log"</span>
 <span class="token boolean">_</span> <span class="token string">"github.com/go-sql-driver/mysql"</span>
 <span class="token string">"github.com/huandu/go-sqlbuilder"</span>
<span class="token punctuation">)</span>
<span class="token keyword">var</span> db <span class="token operator">*</span>sql<span class="token punctuation">.</span>DB
<span class="token keyword">func</span> <span class="token function">init</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">var</span> err <span class="token builtin">error</span>
 db<span class="token punctuation">,</span> err <span class="token operator">=</span> sql<span class="token punctuation">.</span><span class="token function">Open</span><span class="token punctuation">(</span><span class="token string">"mysql"</span><span class="token punctuation">,</span> <span class="token string">"wayne:wayne@/test"</span><span class="token punctuation">)</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Panic</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">// 3 定义结构体</span>
<span class="token keyword">type</span> Emp <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span> <span class="token comment">// 和字段对应的变量或结构体定义，最好和数据库中字段顺序对应</span>
 emp_no     <span class="token builtin">int</span>
 first_name <span class="token builtin">string</span>
 last_name  <span class="token builtin">string</span>
 gender     <span class="token builtin">byte</span>
 birth_date <span class="token builtin">string</span>
 <span class="token comment">// hire_date string</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 query <span class="token operator">:=</span> sqlbuilder<span class="token punctuation">.</span>
 <span class="token function">Select</span><span class="token punctuation">(</span><span class="token string">"emp_no"</span><span class="token punctuation">,</span> <span class="token string">"first_name"</span><span class="token punctuation">,</span> <span class="token string">"last_name"</span><span class="token punctuation">,</span> <span class="token string">"gender"</span><span class="token punctuation">,</span> <span class="token string">"birth_date"</span><span class="token punctuation">)</span><span class="token punctuation">.</span>
 <span class="token function">From</span><span class="token punctuation">(</span><span class="token string">"employees"</span><span class="token punctuation">)</span><span class="token punctuation">.</span>
 <span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"emp_no > 10015"</span><span class="token punctuation">)</span><span class="token punctuation">.</span> <span class="token comment">// 试一试Where("emp_no > ?")</span>
 <span class="token function">Offset</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Limit</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">.</span>
 <span class="token function">OrderBy</span><span class="token punctuation">(</span><span class="token string">"emp_no"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Desc</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span> <span class="token comment">// 按照什么字段排序，降序</span>
 <span class="token function">String</span><span class="token punctuation">(</span><span class="token punctuation">)</span>                  <span class="token comment">// 输出为字符串，底层调用Build()</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>query<span class="token punctuation">)</span>
 rows<span class="token punctuation">,</span> err <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Query</span><span class="token punctuation">(</span>query<span class="token punctuation">)</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
 <span class="token keyword">for</span> rows<span class="token punctuation">.</span><span class="token function">Next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">var</span> emp Emp
 err <span class="token operator">=</span> rows<span class="token punctuation">.</span><span class="token function">Scan</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>emp<span class="token punctuation">.</span>emp_no<span class="token punctuation">,</span> <span class="token operator">&amp;</span>emp<span class="token punctuation">.</span>first_name<span class="token punctuation">,</span> <span class="token operator">&amp;</span>emp<span class="token punctuation">.</span>last_name<span class="token punctuation">,</span>
 <span class="token operator">&amp;</span>emp<span class="token punctuation">.</span>gender<span class="token punctuation">,</span> <span class="token operator">&amp;</span>emp<span class="token punctuation">.</span>birth_date<span class="token punctuation">)</span> <span class="token comment">// 字段顺序和select的字段投影顺序一致</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>emp<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
SELECT emp_no<span class="token punctuation">,</span> first_name<span class="token punctuation">,</span> last_name<span class="token punctuation">,</span> gender<span class="token punctuation">,</span> birth_date FROM employees
WHERE emp_no <span class="token operator">></span> <span class="token number">10015</span> ORDER BY emp_no DESC LIMIT <span class="token number">2</span> OFFSET <span class="token number">2</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>本质上sqlbuilder就是在生成SQL语句字符串。</p>
<p><strong>args参数化</strong></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">builder <span class="token operator">:=</span> sqlbuilder<span class="token punctuation">.</span><span class="token function">Select</span><span class="token punctuation">(</span><span class="token string">"emp_no"</span><span class="token punctuation">,</span> <span class="token string">"first_name"</span><span class="token punctuation">,</span> <span class="token string">"last_name"</span><span class="token punctuation">,</span> <span class="token string">"gender"</span><span class="token punctuation">,</span> <span class="token string">"birth_date"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">From</span><span class="token punctuation">(</span><span class="token string">"employees"</span><span class="token punctuation">)</span>
builder<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span>
    builder<span class="token punctuation">.</span><span class="token function">In</span><span class="token punctuation">(</span><span class="token string">"emp_no"</span><span class="token punctuation">,</span> <span class="token number">10008</span><span class="token punctuation">,</span> <span class="token number">10010</span><span class="token punctuation">,</span> <span class="token number">10020</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token comment">// 参数化</span>
<span class="token punctuation">)</span>
query<span class="token punctuation">,</span> args <span class="token operator">:=</span> builder<span class="token punctuation">.</span><span class="token function">Build</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%s\n%v\n"</span><span class="token punctuation">,</span> query<span class="token punctuation">,</span> args<span class="token punctuation">)</span> <span class="token comment">// args是参数</span>
SELECT emp_no<span class="token punctuation">,</span> first_name<span class="token punctuation">,</span> last_name<span class="token punctuation">,</span> gender<span class="token punctuation">,</span> birth_date FROM employees
WHERE emp_no IN <span class="token punctuation">(</span>?<span class="token punctuation">,</span> ?<span class="token punctuation">,</span> ?<span class="token punctuation">)</span> <span class="token punctuation">[</span><span class="token number">10008</span> <span class="token number">10010</span> <span class="token number">10020</span><span class="token punctuation">]</span>
rows<span class="token punctuation">,</span> err <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Query</span><span class="token punctuation">(</span>query<span class="token punctuation">,</span> args<span class="token operator">...</span><span class="token punctuation">)</span> <span class="token comment">// 这样使用</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h3 id="ORM"><a href="#ORM" class="headerlink" title="ORM"></a>ORM</h3><p>对象关系映射，值得是对象和关系之间的银蛇，使用面相对象的方式操作数据库。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">关系模型和Go对象之间的映射
table <span class="token operator">=</span><span class="token operator">></span> <span class="token keyword">struct</span>   ，表映射为结构体
row   <span class="token operator">=</span><span class="token operator">></span> object   ，行映射为实例
column <span class="token operator">=</span><span class="token operator">></span> property ，字段映射为属性<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>举例，有表student，字段为id  int 、name varchar、age int</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> Student <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 id   <span class="token builtin">int</span>
 name <span class="token builtin">string</span>
 age  <span class="token builtin">int</span>
<span class="token punctuation">&#125;</span>
Student<span class="token punctuation">&#123;</span><span class="token number">100</span><span class="token punctuation">,</span> <span class="token string">"Tom"</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">&#125;</span>
Student<span class="token punctuation">&#123;</span><span class="token number">101</span><span class="token punctuation">,</span> <span class="token string">"Jerry"</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>可以认为ORM是一种高级抽象，对象的操作最终还是会转换成对应关系数据库操作的SQL语句，数据库操作的结构会被封装成对象</p>
<h3 id="GORM-1"><a href="#GORM-1" class="headerlink" title="GORM"></a>GORM</h3><p>GORM是一个友好的、功能全面的、性能不错的基于GO语言实现的ORM库。</p>
<h6 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h6><p>gorm.io&#x2F;dirver&#x2F;mysql 依赖github.com&#x2F;go-sql-driver&#x2F;mysql，可以认为它是对驱动的再封装。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">$ <span class="token keyword">go</span> get <span class="token operator">-</span>u github<span class="token punctuation">.</span>com<span class="token operator">/</span><span class="token keyword">go</span><span class="token operator">-</span>sql<span class="token operator">-</span>driver<span class="token operator">/</span>mysql
$ <span class="token keyword">go</span> get <span class="token operator">-</span>u gorm<span class="token punctuation">.</span>io<span class="token operator">/</span>gorm
$ <span class="token keyword">go</span> get <span class="token operator">-</span>u gorm<span class="token punctuation">.</span>io<span class="token operator">/</span>driver<span class="token operator">/</span>mysql<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h6 id="文档"><a href="#文档" class="headerlink" title="文档"></a>文档</h6><ul>
<li>英文<a target="_blank" rel="noopener" href="https://gorm.io/docs/"> https://gorm.io/docs/</a></li>
<li>中文 <a target="_blank" rel="noopener" href="https://gorm.io/zh_CN/docs/index.html">https://gorm.io/zh_CN&#x2F;docs&#x2F;index.html</a></li>
</ul>
<h6 id="连接"><a href="#连接" class="headerlink" title="连接"></a>连接</h6><p><a target="_blank" rel="noopener" href="https://gorm.io/zh_CN/docs/connecting_to_the_database.html#MySQL">https://gorm.io/zh_CN&#x2F;docs&#x2F;connecting_to_the_database.html#MySQL</a></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main
<span class="token keyword">import</span> <span class="token punctuation">(</span>
 <span class="token string">"fmt"</span>
 <span class="token string">"log"</span>
 <span class="token comment">// _ "github.com/go-sql-driver/mysql" // 不要驱动了吗？</span>
 <span class="token string">"gorm.io/driver/mysql"</span>
 <span class="token string">"gorm.io/gorm"</span>
<span class="token punctuation">)</span>
<span class="token keyword">var</span> db <span class="token operator">*</span>gorm<span class="token punctuation">.</span>DB
<span class="token keyword">func</span> <span class="token function">init</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">var</span> err <span class="token builtin">error</span>
 <span class="token comment">// dsn := "wayne:wayne@/test"</span>
 dsn <span class="token operator">:=</span> <span class="token string">"wayne:wayne@tcp(localhost:3306)/test?charset=utf8mb4"</span>
 db<span class="token punctuation">,</span> err <span class="token operator">=</span> gorm<span class="token punctuation">.</span><span class="token function">Open</span><span class="token punctuation">(</span>mysql<span class="token punctuation">.</span><span class="token function">Open</span><span class="token punctuation">(</span>dsn<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>gorm<span class="token punctuation">.</span>Config<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token comment">// 不要用:=</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Panicln</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>db<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>上面的代码其实还是需要驱动的</p>
<p>在<code>gorm.io/driver/mysql/mysql.go</code>中</p>
<ul>
<li><code>import了&quot;github.com/go-sql-driver/mysql&quot;</code> 也就是说驱动也导入了</li>
<li>Dialector的Initalize方法中使用了<code>sql.Open</code></li>
</ul>
<p><img src="/images/R4_Pj04NJNofQjeP7O098UvyH3-7Mt--bCCv4P-wxa0.png" alt="image"></p>
<p><img src="/images/oYugO6NnOV-fb0qJlsGlfiB7E0wLvwedWxg3qS4kubQ.png" alt="image"></p>
<h5 id="模型定义"><a href="#模型定义" class="headerlink" title="模型定义"></a>模型定义</h5><p><a target="_blank" rel="noopener" href="https://gorm.io/zh_CN/docs/models.html">https://gorm.io/zh_CN&#x2F;docs&#x2F;models.html</a></p>
<p>模型是标准的struct，由Go的基本数据类型、实现了Scanner和Valuer接口的自定义类型及其指针或别名组成</p>
<p>例如：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> User <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
  ID           <span class="token builtin">uint</span>
  Name         <span class="token builtin">string</span>
  Email        <span class="token operator">*</span><span class="token builtin">string</span>
  Age          <span class="token builtin">uint8</span>
  Birthday     <span class="token operator">*</span>time<span class="token punctuation">.</span>Time
  MemberNumber sql<span class="token punctuation">.</span>NullString
  ActivatedAt  sql<span class="token punctuation">.</span>NullTime
  CreatedAt    time<span class="token punctuation">.</span>Time
  UpdatedAt    time<span class="token punctuation">.</span>Time
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>GORM倾向于约定优先配置</p>
<ul>
<li>约定使用名为ID的属性会作为主键</li>
<li>约定使用snake_cases作为表名<ul>
<li>结构体命名为employee，那么数据库表名就是employees</li>
</ul>
</li>
<li>约定使用snake_case作为字段名，字段首字母大写采用大驼峰<ul>
<li>属性名为FirstName，默认对应数据库表的字段名为first_name</li>
</ul>
</li>
</ul>
<p>如果不遵循以上约定就要自定义配置</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 不符合约定的定义，很多都需要配置，直接用不行</span>
<span class="token keyword">type</span> Emp <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span> <span class="token comment">// 默认表名emps</span>
 emp_no     <span class="token builtin">int</span>    <span class="token comment">// 不是ID为主键，需要配置</span>
 first_name <span class="token builtin">string</span> <span class="token comment">// 首字母未大写，也需要配置</span>
 last_name  <span class="token builtin">string</span>
 gender     <span class="token builtin">byte</span>
 birth_date <span class="token builtin">string</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">// 符合约定的定义如下</span>
<span class="token keyword">type</span> student <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span> <span class="token comment">// 默认表名students</span>
 ID   <span class="token builtin">int</span>    <span class="token comment">// Id也可以</span>
 Name <span class="token builtin">string</span> <span class="token comment">// 字段首字母要大写</span>
 Age  <span class="token builtin">int</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="gorm-Model"><a href="#gorm-Model" class="headerlink" title="gorm.Model"></a>gorm.Model</h5><p>GORM定义一个<code>gorm.Model </code>结构体，其包括字段<code>ID、CreateAt、UpdateAt、DeleteAt</code> </p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// gorm.Model 的定义</span>
<span class="token keyword">type</span> Model <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
  ID        <span class="token builtin">uint</span>           <span class="token string">`gorm:"primaryKey"`</span>
  CreatedAt time<span class="token punctuation">.</span>Time
  UpdatedAt time<span class="token punctuation">.</span>Time
  DeletedAt gorm<span class="token punctuation">.</span>DeletedAt <span class="token string">`gorm:"index"`</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="表名配置"><a href="#表名配置" class="headerlink" title="表名配置"></a>表名配置</h5><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 表名并没有遵守约定</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>Emp<span class="token punctuation">)</span> <span class="token function">TableName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">return</span> <span class="token string">"employees"</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="字段配置"><a href="#字段配置" class="headerlink" title="字段配置"></a>字段配置</h5><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main
<span class="token keyword">import</span> <span class="token punctuation">(</span>
 <span class="token string">"fmt"</span>
 <span class="token string">"log"</span>
 <span class="token string">"gorm.io/driver/mysql"</span>
 <span class="token string">"gorm.io/gorm"</span>
 <span class="token string">"gorm.io/gorm/logger"</span>
<span class="token punctuation">)</span>
<span class="token keyword">var</span> db <span class="token operator">*</span>gorm<span class="token punctuation">.</span>DB
<span class="token keyword">func</span> <span class="token function">init</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">var</span> err <span class="token builtin">error</span>
 <span class="token comment">// dsn := "wayne:wayne@/test"</span>
 dsn <span class="token operator">:=</span> <span class="token string">"wayne:wayne@tcp(localhost:3306)/test?charset=utf8mb4"</span>
 db<span class="token punctuation">,</span> err <span class="token operator">=</span> gorm<span class="token punctuation">.</span><span class="token function">Open</span><span class="token punctuation">(</span>mysql<span class="token punctuation">.</span><span class="token function">Open</span><span class="token punctuation">(</span>dsn<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>gorm<span class="token punctuation">.</span>Config<span class="token punctuation">&#123;</span>
 Logger<span class="token punctuation">:</span> logger<span class="token punctuation">.</span>Default<span class="token punctuation">.</span><span class="token function">LogMode</span><span class="token punctuation">(</span>logger<span class="token punctuation">.</span>Info<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token comment">// 日志级别，默认为Silent</span>
即打印慢SQL和错误
 <span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token comment">// 不要用:=</span>
 <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
 log<span class="token punctuation">.</span><span class="token function">Panicln</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">&#125;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>db<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
<span class="token keyword">type</span> Emp <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span> <span class="token comment">// 默认表名emps</span>
 EmpNo     <span class="token builtin">int</span>    <span class="token string">`gorm:"primaryKey"`</span> <span class="token comment">// 默认约束是id为主键，而这里将EmpNo设置为主键，对应库里的字段为emp_no</span>
 FirstName <span class="token builtin">string</span> <span class="token comment">// 首字母大写，对应字段first_name</span>
 LastName  <span class="token builtin">string</span>
 Gender    <span class="token builtin">byte</span>
 BirthDate <span class="token builtin">string</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">// 表名并没有遵守约定</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>Emp<span class="token punctuation">)</span> <span class="token function">TableName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">return</span> <span class="token string">"employees"</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">var</span> e Emp
 result <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Take</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>e<span class="token punctuation">)</span> <span class="token comment">// 等价于Limit 1，取1条</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>result<span class="token punctuation">.</span>Error<span class="token punctuation">)</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>使用<code>gorm:&quot;primaryKey&quot;</code> 来指定字段为主键，默认使用名为ID的属性作为主键。primaryKey是tag名，大小写不敏感，但建议小驼峰</p>
<h5 id="列名"><a href="#列名" class="headerlink" title="列名"></a>列名</h5><p>如果未按照约定定义字段，需要定义结构体属性时指定数据库字段名称是什么</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">BirthDate <span class="token builtin">string</span> <span class="token string">`gorm:"column:birth_date"`</span> <span class="token comment">// 可以使用column指定数据库表中的对应字段名</span>
Xyz <span class="token builtin">string</span> <span class="token string">`gorm:"column:birth_date"`</span> <span class="token comment">// 字段名可以不符合约定，但字段名首字母一定要大写</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>


<h5 id="迁移"><a href="#迁移" class="headerlink" title="迁移"></a>迁移</h5><p><a target="_blank" rel="noopener" href="https://gorm.io/zh_CN/docs/migration.html#%E8%A1%A8">https://gorm.io/zh_CN&#x2F;docs&#x2F;migration.html#%E8%A1%A8</a></p>
<p>下面，新建一个students表，来看看结构体中属性类型和数据库表中字段类型的对应关系</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 迁移后，主键默认不为空，其他字段默认都是能为空的</span>
<span class="token keyword">type</span> Student <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 ID       <span class="token builtin">int</span>       <span class="token comment">// 缺省主键bigint AUTO_INCREMENT</span>
 Name     <span class="token builtin">string</span>    <span class="token string">`gorm:"not null;type:varchar(48);comment:姓名"`</span>
 Age      <span class="token builtin">byte</span>      <span class="token comment">// byte=>tinyint unsigned</span>
 Birthday time<span class="token punctuation">.</span>Time <span class="token comment">// datetime</span>
 Gender   <span class="token builtin">byte</span>      <span class="token string">`gorm:"type:tinyint"`</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">// db.Migrator().DropTable(&amp;Student&#123;&#125;)</span>
db<span class="token punctuation">.</span><span class="token function">Migrator</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">CreateTable</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>Student<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
CREATE TABLE <span class="token string">`students`</span> <span class="token punctuation">(</span>
    <span class="token string">`id`</span> bigint AUTO_INCREMENT<span class="token punctuation">,</span>
    <span class="token string">`name`</span> <span class="token function">varchar</span><span class="token punctuation">(</span><span class="token number">48</span><span class="token punctuation">)</span> NOT NULL COMMENT <span class="token char">'姓名'</span><span class="token punctuation">,</span>
    <span class="token string">`age`</span> tinyint unsigned<span class="token punctuation">,</span>
    <span class="token string">`birthday`</span> <span class="token function">datetime</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span> NULL<span class="token punctuation">,</span>
    <span class="token string">`gender`</span> tinyint<span class="token punctuation">,</span>
    PRIMARY KEY <span class="token punctuation">(</span><span class="token string">`id`</span><span class="token punctuation">)</span> <span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>由于int &#x3D;&gt; bigint、string &#x3D;&gt; longtext，这些默认转换不符合我们的要求，所以，在tag中使用type指定字段类型。</p>
<p>属性是用来构建结构体实例的，生成的SQL语句也要使用这些数据。而tag是用来生成迁移</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">Name    <span class="token builtin">string</span>     <span class="token string">`gorm:"size:48"`</span> 定义为<span class="token function">varchar</span><span class="token punctuation">(</span><span class="token number">48</span><span class="token punctuation">)</span>
Age     <span class="token builtin">int</span>       <span class="token string">`gorm:"size:32"`</span> 定义为<span class="token number">4</span>字节的<span class="token builtin">int</span>
Age     <span class="token builtin">int</span>       <span class="token string">`gorm:"size:64"`</span> 定义为<span class="token number">8</span>字节的bigint<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>迁移功能用的较少。</p>
<p>结构体属性类型用来封装实例的属性数据，Tag中类型指定迁移到数据库表中字段的类型</p>
<h3 id="新增"><a href="#新增" class="headerlink" title="新增"></a>新增</h3><p>参考 <a target="_blank" rel="noopener" href="https://gorm.io/zh_CN/docs/create.html#%E5%88%9B%E5%BB%BA%E8%AE%B0%E5%BD%95">https://gorm.io/zh_CN&#x2F;docs&#x2F;create.html#%E5%88%9B%E5%BB%BA%E8%AE%B0%E5%BD%95</a></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> Student <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 ID       <span class="token builtin">int</span>        <span class="token comment">// 缺省主键bigint AUTO_INCREMENT</span>
 Name     <span class="token builtin">string</span>     <span class="token string">`gorm:"size:48"`</span> <span class="token comment">//`gorm:"not null;type:varchar(48);comment:姓名"`</span>
 Age      <span class="token builtin">byte</span>       <span class="token comment">// byte=>tinyint unsigned</span>
 Birthday <span class="token operator">*</span>time<span class="token punctuation">.</span>Time <span class="token comment">// datetime</span>
 Gender   <span class="token builtin">byte</span>       <span class="token comment">//`gorm:"type:tinyint"`</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>s <span class="token operator">*</span>Student<span class="token punctuation">)</span> <span class="token function">String</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">return</span> fmt<span class="token punctuation">.</span><span class="token function">Sprintf</span><span class="token punctuation">(</span><span class="token string">"%d: %s %d"</span><span class="token punctuation">,</span> s<span class="token punctuation">.</span>ID<span class="token punctuation">,</span> s<span class="token punctuation">.</span>Name<span class="token punctuation">,</span> s<span class="token punctuation">.</span>Age<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="新增一条"><a href="#新增一条" class="headerlink" title="新增一条"></a>新增一条</h5><pre class="line-numbers language-go" data-language="go"><code class="language-go">t <span class="token operator">:=</span> time<span class="token punctuation">.</span><span class="token function">Now</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
s <span class="token operator">:=</span> Student<span class="token punctuation">&#123;</span>Name<span class="token punctuation">:</span> <span class="token string">"Tom"</span><span class="token punctuation">,</span> Age<span class="token punctuation">:</span> <span class="token number">20</span><span class="token punctuation">,</span> Birthday<span class="token punctuation">:</span> <span class="token operator">&amp;</span>t<span class="token punctuation">&#125;</span>
result <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Create</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>s<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>result<span class="token punctuation">.</span>RowsAffected<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="新增多条"><a href="#新增多条" class="headerlink" title="新增多条"></a>新增多条</h5><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 新增多条</span>
n <span class="token operator">:=</span> time<span class="token punctuation">.</span><span class="token function">Now</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
s <span class="token operator">:=</span> Student<span class="token punctuation">&#123;</span>Name<span class="token punctuation">:</span> <span class="token string">"Tom"</span><span class="token punctuation">,</span> Age<span class="token punctuation">:</span> <span class="token number">20</span><span class="token punctuation">,</span> Birthday<span class="token punctuation">:</span> <span class="token operator">&amp;</span>n<span class="token punctuation">&#125;</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span>
result <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Create</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>Student<span class="token punctuation">&#123;</span><span class="token operator">&amp;</span>s<span class="token punctuation">,</span> <span class="token operator">&amp;</span>s<span class="token punctuation">,</span> <span class="token operator">&amp;</span>s<span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token comment">// 传入指针的切片</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>result<span class="token punctuation">.</span>Error<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>result<span class="token punctuation">.</span>RowsAffected<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h5 id="查询一条"><a href="#查询一条" class="headerlink" title="查询一条"></a>查询一条</h5><p>Take 被转换为Limit 1</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">var</span> s Student
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span> <span class="token comment">// 零值</span>
r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Take</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>s<span class="token punctuation">)</span> <span class="token comment">// LIMIT 1</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span> <span class="token comment">// 被填充</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>r<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>r<span class="token punctuation">.</span>Error<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">First</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>s<span class="token punctuation">)</span> <span class="token comment">// ORDER BY `students`.`id` LIMIT 1</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Last</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>s<span class="token punctuation">)</span> <span class="token comment">// ORDER BY `students`.`id` DESC LIMIT 1</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>根据id查，可以使用下面的方式</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">First</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>s<span class="token punctuation">,</span> <span class="token number">15</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">var</span> a <span class="token operator">=</span> Student<span class="token punctuation">&#123;</span>Id<span class="token punctuation">:</span> <span class="token number">25</span><span class="token punctuation">&#125;</span>
results <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Take</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>a<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>results<span class="token punctuation">.</span>RowsAffected<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>


<h5 id="时间相关错误"><a href="#时间相关错误" class="headerlink" title="时间相关错误"></a>时间相关错误</h5><p>1、时间类型字段</p>
<p>上例错误如下，主要是使用了*time.Time，而不是string</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">sql<span class="token punctuation">:</span> Scan <span class="token builtin">error</span> on column index <span class="token number">3</span><span class="token punctuation">,</span> name <span class="token string">"birthday"</span><span class="token punctuation">:</span> unsupported Scan<span class="token punctuation">,</span> storing 
driver<span class="token punctuation">.</span>Value <span class="token keyword">type</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">uint8</span> into <span class="token keyword">type</span> <span class="token operator">*</span>time<span class="token punctuation">.</span>Time
<span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span> 转 <span class="token operator">*</span>time<span class="token punctuation">.</span>Time失败了<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>解决方案</p>
<ul>
<li>在连接字符串中增加parseTime&#x3D;true ，这样时间类型就会自动转化为time.Time类型<ul>
<li><code>dsn := &quot;wayne:wayne@tcp(localhost:3306)/test?charset=utf8mb4&amp;parseTime=true&quot;</code></li>
</ul>
</li>
<li>也可以<code>Birthday string</code> ，拿到Birthday字符串后，必要时，转换成时间类型,time.Parse()</li>
</ul>
<p><strong>2、UTC时间</strong></p>
<p>Create写入的时间，也就是说time.Now()取当前时区时间，但是存入数据库的时间是UTC时间。</p>
<p>Take拿回的时间也是UTC时间，可以通过<code>s.Birthday.Local()</code>转换成当前时区时间。</p>
<p>如果想要存入的时间或读取的时间直接是当前时区时间，可以使用loc参数loc&#x3D;Local</p>
<p>如果使用了loc&#x3D;Local</p>
<ul>
<li>存入时，数据库字段中的时间就是当前时区的时间值</li>
<li>读取时，数据库字段中的时间就被解读为当前时区</li>
</ul>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">dsn <span class="token operator">:=</span> "wayne<span class="token punctuation">:</span>wayne@<span class="token function">tcp</span><span class="token punctuation">(</span>localhost<span class="token punctuation">:</span><span class="token number">3306</span><span class="token punctuation">)</span><span class="token operator">/</span>test?
charset<span class="token operator">=</span>utf8mb4<span class="token operator">&amp;</span>parseTime<span class="token operator">=</span><span class="token boolean">true</span><span class="token operator">&amp;</span>loc<span class="token operator">=</span>Local"
<span class="token comment">// time/zoneinfo.go</span>
<span class="token keyword">func</span> <span class="token function">LoadLocation</span><span class="token punctuation">(</span>name <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token operator">*</span>Location<span class="token punctuation">,</span> <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">if</span> name <span class="token operator">==</span> <span class="token string">""</span> <span class="token operator">||</span> name <span class="token operator">==</span> <span class="token string">"UTC"</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">return</span> UTC<span class="token punctuation">,</span> <span class="token boolean">nil</span>
 <span class="token punctuation">&#125;</span>
 <span class="token keyword">if</span> name <span class="token operator">==</span> <span class="token string">"Local"</span> <span class="token punctuation">&#123;</span>
 <span class="token keyword">return</span> Local<span class="token punctuation">,</span> <span class="token boolean">nil</span>
 <span class="token punctuation">&#125;</span>
 <span class="token operator">...</span>省略
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>千万不要存入数据库时采用Local存入，却使用UTC解读时间，会造成时间时区的混乱。应该保证时间存入、读取时时区一致</strong></p>
<p>一定要统一项目中数据库中时间类型字段的时区。可以考虑统一采用UTC，为了本地化显示转换为当前时区即可。</p>
<h5 id="查询所有"><a href="#查询所有" class="headerlink" title="查询所有"></a>查询所有</h5><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">var</span> students <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>Student
r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>students<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>r<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>r<span class="token punctuation">.</span>Error<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>students<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="distinct"><a href="#distinct" class="headerlink" title="distinct"></a>distinct</h5><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">var</span> students <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>Student
r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Distinct</span><span class="token punctuation">(</span><span class="token string">"name"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>students<span class="token punctuation">)</span> <span class="token comment">// 投影的字段是什么？</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>students<span class="token punctuation">)</span> <span class="token comment">// 容器里每个实例是什么样子？</span>

<span class="token comment">// 输出</span>
<span class="token number">2023</span><span class="token operator">/</span><span class="token number">07</span><span class="token operator">/</span><span class="token number">31</span> <span class="token number">14</span><span class="token punctuation">:</span><span class="token number">34</span><span class="token punctuation">:</span><span class="token number">13</span> <span class="token operator">/</span>Users<span class="token operator">/</span>dujie<span class="token operator">/</span>Desktop<span class="token operator">/</span>go12<span class="token operator">/</span>goproject<span class="token operator">/</span>mysql<span class="token operator">-</span>test<span class="token operator">/</span>main<span class="token punctuation">.</span><span class="token keyword">go</span><span class="token punctuation">:</span><span class="token number">75</span>
<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">.</span>602ms<span class="token punctuation">]</span> <span class="token punctuation">[</span>rows<span class="token punctuation">:</span><span class="token number">9</span><span class="token punctuation">]</span> SELECT DISTINCT <span class="token string">`name`</span> FROM <span class="token string">`students`</span>
<span class="token punctuation">[</span><span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">0</span> Tom <span class="token number">0</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">0</span> 张三 <span class="token number">0</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">0</span> 李四 <span class="token number">0</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">0</span> 收到 <span class="token number">0</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">0</span> 陈飞 <span class="token number">0</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">0</span> 周正 <span class="token number">0</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">0</span> Tom1 <span class="token number">0</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">0</span> Tom2 <span class="token number">0</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">0</span> Tom3 <span class="token number">0</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span><span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="投影"><a href="#投影" class="headerlink" title="投影"></a>投影</h5><p>投影是关系模型的操作，就是选择哪些字段</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">var</span> students <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>Student
r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Select</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">,</span> <span class="token string">"name"</span><span class="token punctuation">,</span> <span class="token string">"age"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>students<span class="token punctuation">)</span> r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Select</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">&#123;</span><span class="token string">"id"</span><span class="token punctuation">,</span> <span class="token string">"name"</span><span class="token punctuation">,</span> <span class="token string">"age"</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>students<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>students<span class="token punctuation">)</span>
<span class="token comment">// 输出</span>
<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">.</span>580ms<span class="token punctuation">]</span> <span class="token punctuation">[</span>rows<span class="token punctuation">:</span><span class="token number">27</span><span class="token punctuation">]</span> SELECT <span class="token string">`id`</span><span class="token punctuation">,</span><span class="token string">`name`</span><span class="token punctuation">,</span><span class="token string">`age`</span> FROM <span class="token string">`students`</span>
<span class="token punctuation">[</span><span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">1</span> Tom <span class="token number">32</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">2</span> Tom <span class="token number">32</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">3</span> Tom <span class="token number">32</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">4</span> Tom <span class="token number">32</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">5</span> Tom <span class="token number">32</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">6</span> Tom <span class="token number">32</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">7</span> Tom <span class="token number">32</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">8</span> Tom <span class="token number">32</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">9</span> Tom <span class="token number">32</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">10</span> Tom <span class="token number">32</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">11</span> Tom <span class="token number">0</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">12</span> Tom <span class="token number">0</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">13</span> Tom <span class="token number">0</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">14</span> 张三 <span class="token number">33</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">15</span> 李四 <span class="token number">39</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">16</span> 李四 <span class="token number">39</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">17</span> 李四 <span class="token number">39</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">18</span> 李四 <span class="token number">39</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">19</span> 收到 <span class="token number">39</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">20</span> 陈飞 <span class="token number">32</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">21</span> 周正 <span class="token number">18</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">22</span> 周正 <span class="token number">18</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">23</span> 周正 <span class="token number">18</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">24</span> Tom <span class="token number">20</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">25</span> Tom1 <span class="token number">201</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">26</span> Tom2 <span class="token number">202</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">27</span> Tom3 <span class="token number">203</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">0</span><span class="token operator">></span><span class="token punctuation">]</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="Limit和Offset"><a href="#Limit和Offset" class="headerlink" title="Limit和Offset"></a>Limit和Offset</h5><pre class="line-numbers language-go" data-language="go"><code class="language-go">    <span class="token keyword">var</span> students <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>Student
    db<span class="token punctuation">.</span><span class="token function">Limit</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Offset</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>students<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>students<span class="token punctuation">)</span> <span class="token comment">// 容器里每个实例是什么样子？</span>

<span class="token comment">// 输出</span>
<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">.</span>534ms<span class="token punctuation">]</span> <span class="token punctuation">[</span>rows<span class="token punctuation">:</span><span class="token number">2</span><span class="token punctuation">]</span> SELECT <span class="token operator">*</span> FROM <span class="token string">`students`</span> LIMIT <span class="token number">2</span> OFFSET <span class="token number">2</span>
<span class="token punctuation">[</span><span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">3</span> Tom <span class="token number">32</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">1</span><span class="token operator">></span> <span class="token operator">&lt;</span>Id<span class="token punctuation">:</span><span class="token number">4</span> Tom <span class="token number">32</span> <span class="token operator">&lt;</span><span class="token boolean">nil</span><span class="token operator">></span> <span class="token number">1</span><span class="token operator">></span><span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h5 id="条件查询"><a href="#条件查询" class="headerlink" title="条件查询"></a>条件查询</h5><p><strong>1、字符串条件</strong></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">var</span> stu <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>Student
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name = ?"</span><span class="token punctuation">,</span> <span class="token string">"陈飞"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name &lt;> ?"</span><span class="token punctuation">,</span> <span class="token string">"Tom"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>                              <span class="token comment">// 不等于</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name in (?)"</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">&#123;</span><span class="token string">"张三"</span><span class="token punctuation">,</span> <span class="token string">"陈飞"</span><span class="token punctuation">,</span> <span class="token string">"周正"</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span> <span class="token comment">//  在...中</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name like ?"</span><span class="token punctuation">,</span> <span class="token string">"周%"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span> <span class="token comment">// 模糊查询</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name like binary ?"</span><span class="token punctuation">,</span> <span class="token string">"T%"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name like ? or name like ?"</span><span class="token punctuation">,</span> <span class="token string">"张三"</span><span class="token punctuation">,</span> <span class="token string">"李四"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name like ? or id = ?"</span><span class="token punctuation">,</span> <span class="token string">"陈飞"</span><span class="token punctuation">,</span> <span class="token number">9</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"id between ? and ?"</span><span class="token punctuation">,</span> <span class="token number">15</span><span class="token punctuation">,</span> <span class="token number">17</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>stu<span class="token punctuation">)</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>2、struct或map条件</strong></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">var</span> stu <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>Student
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name = ?"</span><span class="token punctuation">,</span> <span class="token string">"陈飞"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name &lt;> ?"</span><span class="token punctuation">,</span> <span class="token string">"Tom"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>                              <span class="token comment">// 不等于</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name in (?)"</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">&#123;</span><span class="token string">"张三"</span><span class="token punctuation">,</span> <span class="token string">"陈飞"</span><span class="token punctuation">,</span> <span class="token string">"周正"</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span> <span class="token comment">//  在...中</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name like ?"</span><span class="token punctuation">,</span> <span class="token string">"周%"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>                            <span class="token comment">// 模糊查询</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name like binary ?"</span><span class="token punctuation">,</span> <span class="token string">"T%"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name like ? or name like ?"</span><span class="token punctuation">,</span> <span class="token string">"张三"</span><span class="token punctuation">,</span> <span class="token string">"李四"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name like ? or id = ?"</span><span class="token punctuation">,</span> <span class="token string">"陈飞"</span><span class="token punctuation">,</span> <span class="token number">9</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"id between ? and ?"</span><span class="token punctuation">,</span> <span class="token number">15</span><span class="token punctuation">,</span> <span class="token number">17</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">&#123;</span><span class="token number">14</span><span class="token punctuation">,</span> <span class="token number">15</span><span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>Student<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>Student<span class="token punctuation">&#123;</span>Id<span class="token punctuation">:</span> <span class="token number">18</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>Student<span class="token punctuation">&#123;</span>Id<span class="token punctuation">:</span> <span class="token number">19</span><span class="token punctuation">,</span> Name<span class="token punctuation">:</span> <span class="token string">"陈飞"</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>                   <span class="token comment">// And</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token keyword">map</span><span class="token punctuation">[</span><span class="token builtin">string</span><span class="token punctuation">]</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#123;</span><span class="token string">"name"</span><span class="token punctuation">:</span> <span class="token string">"陈飞"</span><span class="token punctuation">,</span> <span class="token string">"id"</span><span class="token punctuation">:</span> <span class="token number">20</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span> <span class="token comment">// And</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>stu<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>struct条件中出现了零值，例如<code>db.Where(&amp;Student&#123;Name:&quot;tom&quot;,Age: 0&#125;)</code> ，Age是零值，就不会出现在条件中。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>Student<span class="token punctuation">&#123;</span>Name<span class="token punctuation">:</span> <span class="token string">"Tom"</span><span class="token punctuation">,</span> Age<span class="token punctuation">:</span> <span class="token number">20</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token string">"name"</span><span class="token punctuation">,</span> <span class="token string">"age"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>students<span class="token punctuation">)</span> 
<span class="token comment">// 指定使用结构体里面的name和age字段作为条件，and</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p><strong>3、Not</strong></p>
<p>将Where换成Not即可，表示条件取反</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">db<span class="token punctuation">.</span><span class="token function">Not</span><span class="token punctuation">(</span><span class="token string">"id =? or id in (?)"</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">&#123;</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">,</span> <span class="token number">8</span><span class="token punctuation">,</span> <span class="token number">9</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">11</span><span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">,</span> <span class="token number">13</span><span class="token punctuation">,</span> <span class="token number">14</span><span class="token punctuation">,</span> <span class="token number">15</span><span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">,</span> <span class="token number">17</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">,</span> <span class="token number">19</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>stu<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p><strong>4、Or</strong></p>
<p>Or的用法和Where一样</p>
<p>Where().Where() 是And关系，Where().Or()是Or关系</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name=?"</span><span class="token punctuation">,</span> <span class="token string">"周正"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Or</span><span class="token punctuation">(</span><span class="token string">"name=?"</span><span class="token punctuation">,</span> <span class="token string">"陈飞"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span>
db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"name=?"</span><span class="token punctuation">,</span> <span class="token string">"周正"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Or</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>Student<span class="token punctuation">&#123;</span>Name<span class="token punctuation">:</span> <span class="token string">"Tom"</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stu<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h5 id="排序"><a href="#排序" class="headerlink" title="排序"></a>排序</h5><pre class="line-numbers language-go" data-language="go"><code class="language-go">r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Order</span><span class="token punctuation">(</span><span class="token string">"id desc"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>students<span class="token punctuation">)</span> <span class="token comment">// ORDER BY id desc</span>
r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Order</span><span class="token punctuation">(</span><span class="token string">"name, id desc"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>students<span class="token punctuation">)</span>         <span class="token comment">// ORDER BY name,id desc</span>
r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Order</span><span class="token punctuation">(</span><span class="token string">"name"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Order</span><span class="token punctuation">(</span><span class="token string">"id desc"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>students<span class="token punctuation">)</span> <span class="token comment">// ORDER BY name,id desc</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h5 id="分组"><a href="#分组" class="headerlink" title="分组"></a>分组</h5><pre class="line-numbers language-go" data-language="go"><code class="language-go">r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Group</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>students<span class="token punctuation">)</span> <span class="token comment">// GROUP BY `id`</span>
r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Group</span><span class="token punctuation">(</span><span class="token string">"name"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>students<span class="token punctuation">)</span> <span class="token comment">// GROUP BY `name`</span>
r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Group</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Group</span><span class="token punctuation">(</span><span class="token string">"name"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>students<span class="token punctuation">)</span> <span class="token comment">// GROUP BY `id`,`name`</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// SELECT name, count(id) as c FROM `students` GROUP BY `name`</span>
r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Select</span><span class="token punctuation">(</span><span class="token string">"name, count(id) as c"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Group</span><span class="token punctuation">(</span><span class="token string">"name"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>students<span class="token punctuation">)</span>
<span class="token comment">// 但是students中没有属性来保存count的值</span>
<span class="token comment">// 使用Rows()返回所有行，自行获取字段值，但是要用Table指定表名</span>
<span class="token keyword">type</span> Result <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
    name  <span class="token builtin">string</span>
    count <span class="token builtin">int</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">var</span> r <span class="token operator">=</span> Result<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
rows<span class="token punctuation">,</span> err <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Table</span><span class="token punctuation">(</span><span class="token string">"students"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Select</span><span class="token punctuation">(</span>"name<span class="token punctuation">,</span> <span class="token function">count</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span> as 
c<span class="token string">").Group("</span>name"<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Rows</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
<span class="token comment">// 遍历每一行，填充2个属性的结构体实例</span>
<span class="token keyword">for</span> rows<span class="token punctuation">.</span><span class="token function">Next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    rows<span class="token punctuation">.</span><span class="token function">Scan</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>r<span class="token punctuation">.</span>name<span class="token punctuation">,</span> <span class="token operator">&amp;</span>r<span class="token punctuation">.</span>count<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>r<span class="token punctuation">,</span> <span class="token string">"@@@"</span><span class="token punctuation">)</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> Result <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span> <span class="token comment">// 和Select的投影字段对应</span>
    Name  <span class="token builtin">string</span>
    Count <span class="token builtin">int</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">var</span> r <span class="token operator">=</span> Result<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
rows<span class="token punctuation">,</span> err <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Table</span><span class="token punctuation">(</span><span class="token string">"students"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Select</span><span class="token punctuation">(</span><span class="token string">"name, count(id) as c"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Group</span><span class="token punctuation">(</span><span class="token string">"name"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Having</span><span class="token punctuation">(</span><span class="token string">"c > 3"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Rows</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
<span class="token comment">// 遍历每一行，填充2个属性的结构体实例</span>
<span class="token keyword">for</span> rows<span class="token punctuation">.</span><span class="token function">Next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    rows<span class="token punctuation">.</span><span class="token function">Scan</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>r<span class="token punctuation">.</span>Name<span class="token punctuation">,</span> <span class="token operator">&amp;</span>r<span class="token punctuation">.</span>Count<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>r<span class="token punctuation">,</span> <span class="token string">"@@@"</span><span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
<span class="token comment">// 使用Scan填充容器，注意字段名要大写开头</span>
<span class="token keyword">type</span> Result <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
    Name <span class="token builtin">string</span>
    C    <span class="token builtin">int</span> <span class="token comment">// 或Count int `gorm:"column:c"`</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">var</span> rows <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>Result<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
db<span class="token punctuation">.</span><span class="token function">Table</span><span class="token punctuation">(</span><span class="token string">"students"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Select</span><span class="token punctuation">(</span><span class="token string">"name, count(id) as c"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Group</span><span class="token punctuation">(</span><span class="token string">"name"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Having</span><span class="token punctuation">(</span><span class="token string">"c > 3"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Scan</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>rows<span class="token punctuation">)</span>
<span class="token keyword">for</span> i<span class="token punctuation">,</span> r <span class="token operator">:=</span> <span class="token keyword">range</span> rows <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">"%d, %T %#[2]v\n"</span><span class="token punctuation">,</span> i<span class="token punctuation">,</span> r<span class="token punctuation">)</span> 
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h5 id="Join"><a href="#Join" class="headerlink" title="Join"></a>Join</h5><pre class="line-numbers language-go" data-language="go"><code class="language-go">SELECT
 employees<span class="token punctuation">.</span>emp_no<span class="token punctuation">,</span> 
 employees<span class="token punctuation">.</span>first_name<span class="token punctuation">,</span> 
 employees<span class="token punctuation">.</span>last_name<span class="token punctuation">,</span> 
 salaries<span class="token punctuation">.</span>salary
FROM
 employees
 INNER JOIN
 salaries
 ON
 employees<span class="token punctuation">.</span>emp_no <span class="token operator">=</span> salaries<span class="token punctuation">.</span>emp_no<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> Result <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
    EmpNo     <span class="token builtin">int</span>
    FirstName <span class="token builtin">string</span>
    LastName  <span class="token builtin">string</span>
    Salary    <span class="token builtin">int</span>
<span class="token punctuation">&#125;</span>
rows<span class="token punctuation">,</span> err <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Table</span><span class="token punctuation">(</span><span class="token string">"employees as e"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Select</span><span class="token punctuation">(</span>"e<span class="token punctuation">.</span>emp_no<span class="token punctuation">,</span> first_name<span class="token punctuation">,</span> 
last_name<span class="token punctuation">,</span> salary"<span class="token punctuation">)</span><span class="token punctuation">.</span>
<span class="token function">Joins</span><span class="token punctuation">(</span><span class="token string">"join salaries as s on e.emp_no = s.emp_no"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Rows</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
<span class="token keyword">var</span> r Result
<span class="token keyword">for</span> rows<span class="token punctuation">.</span><span class="token function">Next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    rows<span class="token punctuation">.</span><span class="token function">Scan</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>r<span class="token punctuation">.</span>EmpNo<span class="token punctuation">,</span> <span class="token operator">&amp;</span>r<span class="token punctuation">.</span>FirstName<span class="token punctuation">,</span> <span class="token operator">&amp;</span>r<span class="token punctuation">.</span>LastName<span class="token punctuation">,</span> <span class="token operator">&amp;</span>r<span class="token punctuation">.</span>Salary<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>r<span class="token punctuation">,</span> <span class="token string">"###"</span><span class="token punctuation">)</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> Result <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
 EmpNo     <span class="token builtin">int</span>
 FirstName <span class="token builtin">string</span>
 LastName  <span class="token builtin">string</span>
 Salary    <span class="token builtin">int</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">var</span> results <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>Result<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Table</span><span class="token punctuation">(</span><span class="token string">"employees as e"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Select</span><span class="token punctuation">(</span>"e<span class="token punctuation">.</span>emp_no<span class="token punctuation">,</span> first_name<span class="token punctuation">,</span> last_name<span class="token punctuation">,</span> 
salary"<span class="token punctuation">)</span><span class="token punctuation">.</span>
 <span class="token function">Joins</span><span class="token punctuation">(</span><span class="token string">"join salaries on e.emp_no = salaries.emp_no"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>results<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>r<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>r<span class="token punctuation">.</span>Error<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>r<span class="token punctuation">.</span>RowsAffected<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"~~~~~~~~~~~~~~~~~~~~~~~~~~~"</span><span class="token punctuation">)</span>
<span class="token keyword">for</span> i<span class="token punctuation">,</span> row <span class="token operator">:=</span> <span class="token keyword">range</span> results <span class="token punctuation">&#123;</span>
 fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>i<span class="token punctuation">,</span> row<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> Result <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
    EmpNo     <span class="token builtin">int</span>
    FirstName <span class="token builtin">string</span>
    LastName  <span class="token builtin">string</span>
    Salary    <span class="token builtin">int</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">var</span> results <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token operator">*</span>Result<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
db<span class="token punctuation">.</span><span class="token function">Table</span><span class="token punctuation">(</span><span class="token string">"employees as e"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Select</span><span class="token punctuation">(</span>"e<span class="token punctuation">.</span>emp_no<span class="token punctuation">,</span> first_name<span class="token punctuation">,</span> last_name<span class="token punctuation">,</span> 
salary"<span class="token punctuation">)</span><span class="token punctuation">.</span>
<span class="token function">Joins</span><span class="token punctuation">(</span><span class="token string">"join salaries as s on e.emp_no = s.emp_no"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Scan</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>results<span class="token punctuation">)</span>
<span class="token keyword">for</span> i<span class="token punctuation">,</span> r <span class="token operator">:=</span> <span class="token keyword">range</span> results <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>i<span class="token punctuation">,</span> r<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h5 id="更新"><a href="#更新" class="headerlink" title="更新"></a>更新</h5><p><a target="_blank" rel="noopener" href="https://gorm.io/zh_CN/docs/update.html">https://gorm.io/zh_CN&#x2F;docs&#x2F;update.html</a></p>
<p>先查后改：先查到一个实例，对这个实例属性进行修改，然后调用db.Save()方法保存。</p>
<p>db.Save()方法会保存所有字段，对于没有主键的实例相当于Insert into，有主键的实例相当于Update。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 先查</span>
<span class="token keyword">var</span> student Student
db<span class="token punctuation">.</span><span class="token function">First</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>student<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>student<span class="token punctuation">)</span>
student<span class="token punctuation">.</span>Age <span class="token operator">+=</span> <span class="token number">10</span>
student<span class="token punctuation">.</span>Name <span class="token operator">=</span> <span class="token string">"Sam"</span>
<span class="token comment">// 后修改</span>
db<span class="token punctuation">.</span><span class="token function">Save</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>student<span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>student<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<p>Update 单个字段</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Model</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>Student<span class="token punctuation">&#123;</span>ID<span class="token punctuation">:</span> <span class="token number">13</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Update</span><span class="token punctuation">(</span><span class="token string">"age"</span><span class="token punctuation">,</span> <span class="token number">11</span><span class="token punctuation">)</span> <span class="token comment">// 更新符合条件的所有记录的一个</span>
字段
<span class="token comment">// UPDATE `students` SET `age`=11 WHERE `id` = 13</span>
r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Model</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>Student<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Update</span><span class="token punctuation">(</span><span class="token string">"age"</span><span class="token punctuation">,</span> <span class="token number">11</span><span class="token punctuation">)</span> <span class="token comment">// 没有指定ID或Where条件，是全表更新</span>
age字段，这是非常危险的
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>r<span class="token punctuation">.</span>Error<span class="token punctuation">)</span> <span class="token comment">// 会报WHERE conditions required错误，更新失败，这是一种保护</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<p>Update更新多列</p>
<p>多个键值对，使用map或结构体实例传参</p>
<p>同样，没有指定ID或where条件，是全表更新age字段，这是非常危险的，报WHERE conditions required错误</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Model</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>Student<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"age &lt; ?"</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Updates</span><span class="token punctuation">(</span><span class="token keyword">map</span><span class="token punctuation">[</span><span class="token builtin">string</span><span class="token punctuation">]</span><span class="token keyword">interface</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#123;</span><span class="token string">"name"</span><span class="token punctuation">:</span> <span class="token string">"John"</span><span class="token punctuation">,</span> <span class="token string">"age"</span><span class="token punctuation">:</span> <span class="token number">23</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>r<span class="token punctuation">.</span>Error<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">r <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Model</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>Student<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"age &lt; ?"</span><span class="token punctuation">,</span> <span class="token number">24</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Updates</span><span class="token punctuation">(</span>Student<span class="token punctuation">&#123;</span>Name<span class="token punctuation">:</span> <span class="token string">"John"</span><span class="token punctuation">,</span> Age<span class="token punctuation">:</span><span class="token number">18</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>r<span class="token punctuation">.</span>Error<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h5 id="删除"><a href="#删除" class="headerlink" title="删除"></a>删除</h5><p><a target="_blank" rel="noopener" href="https://gorm.io/zh_CN/docs/delete.html">https://gorm.io/zh_CN&#x2F;docs&#x2F;delete.html</a></p>
<p>删除操作是危险的，慎重操作！</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">result <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Delete</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>Student<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>result<span class="token punctuation">.</span>Error<span class="token punctuation">)</span>
<span class="token comment">// 报WHERE conditions required错误，这是全表删除，危险</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">result <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Delete</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>Student<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token number">15</span><span class="token punctuation">)</span> <span class="token comment">// 指定主键</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>result<span class="token punctuation">.</span>Error<span class="token punctuation">)</span>
db<span class="token punctuation">.</span><span class="token function">Delete</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>Student<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">&#123;</span><span class="token number">15</span><span class="token punctuation">,</span> <span class="token number">16</span><span class="token punctuation">,</span> <span class="token number">18</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token comment">// DELETE FROM `students` WHERE `students`.`id` IN (15,16,18)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">result <span class="token operator">:=</span> db<span class="token punctuation">.</span><span class="token function">Where</span><span class="token punctuation">(</span><span class="token string">"id > ?"</span><span class="token punctuation">,</span> <span class="token number">15</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Delete</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>Student<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span> <span class="token comment">// 删除符合条件的一批</span>
fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>result<span class="token punctuation">.</span>Error<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>


























































</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love">J.</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love/2023/05/06/Golang%E4%B8%AD%E7%9A%84GORM/">http://dycloudnavite.love/2023/05/06/Golang%E4%B8%AD%E7%9A%84GORM/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://dycloudnavite.love" target="_blank">J.のblog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/dujie5416/tags/%E4%BA%91%E5%8E%9F%E7%94%9F/">云原生</a><a class="post-meta__tags" href="/dujie5416/tags/golang/">golang</a></div><div class="post_share"><div class="addthis_inline_share_toolbox"></div><script src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5d034d84b42927bf" async="async"></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/dujie5416/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/dujie5416/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/dujie5416/2023/05/09/Go%E6%93%8D%E4%BD%9CMongoDB/"><img class="prev-cover" src="/dujie5416/img/golang.png" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Golang 操作MongoDB</div></div></a></div><div class="next-post pull-right"><a href="/dujie5416/2023/05/03/Golang%E6%95%B0%E6%8D%AE%E5%BA%93%E6%A0%87%E5%87%86%E5%BC%80%E5%8F%91/"><img class="next-cover" src="/dujie5416/img/golang.png" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Golang 数据库标准开发</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/dujie5416/2023/05/20/Channel%E9%80%9A%E9%81%93/" title="Channel通道"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-20</div><div class="title">Channel通道</div></div></a></div><div><a href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-06-23</div><div class="title">Gin框架</div></div></a></div><div><a href="/dujie5416/2023/05/15/Golang%E5%8D%8F%E7%A8%8B/" title="Golang协程"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-15</div><div class="title">Golang协程</div></div></a></div><div><a href="/dujie5416/2023/04/17/Golang%E5%8F%98%E9%87%8F%E9%80%83%E9%80%B8%E2%80%94%E2%80%94%E5%A0%86%E3%80%81%E6%A0%88/" title="Golang变量逃逸————堆、栈"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-04-17</div><div class="title">Golang变量逃逸————堆、栈</div></div></a></div><div><a href="/dujie5416/2023/02/13/Golang%E5%AD%97%E7%AC%A6%E4%B8%B2string/" title="Golang字符串"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-13</div><div class="title">Golang字符串</div></div></a></div><div><a href="/dujie5416/2023/04/15/Golang%20List/" title="Golang List"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-04-15</div><div class="title">Golang List</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="lv-container" data-id="city" data-uid="MTAyMC81Njk5OS8zMzQ2Mw=="></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/dujie5416/img/touxiang.png" onerror="this.onerror=null;this.src='/dujie5416/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">J.</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#GORM"><span class="toc-number">1.</span> <span class="toc-text">GORM</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#SQLBuilder"><span class="toc-number">1.0.1.</span> <span class="toc-text">SQLBuilder</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ORM"><span class="toc-number">1.0.2.</span> <span class="toc-text">ORM</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#GORM-1"><span class="toc-number">1.0.3.</span> <span class="toc-text">GORM</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#%E5%AE%89%E8%A3%85"><span class="toc-number">1.0.3.0.0.1.</span> <span class="toc-text">安装</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#%E6%96%87%E6%A1%A3"><span class="toc-number">1.0.3.0.0.2.</span> <span class="toc-text">文档</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#%E8%BF%9E%E6%8E%A5"><span class="toc-number">1.0.3.0.0.3.</span> <span class="toc-text">连接</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%A8%A1%E5%9E%8B%E5%AE%9A%E4%B9%89"><span class="toc-number">1.0.3.0.1.</span> <span class="toc-text">模型定义</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#gorm-Model"><span class="toc-number">1.0.3.0.2.</span> <span class="toc-text">gorm.Model</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%A1%A8%E5%90%8D%E9%85%8D%E7%BD%AE"><span class="toc-number">1.0.3.0.3.</span> <span class="toc-text">表名配置</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%AD%97%E6%AE%B5%E9%85%8D%E7%BD%AE"><span class="toc-number">1.0.3.0.4.</span> <span class="toc-text">字段配置</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%88%97%E5%90%8D"><span class="toc-number">1.0.3.0.5.</span> <span class="toc-text">列名</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%BF%81%E7%A7%BB"><span class="toc-number">1.0.3.0.6.</span> <span class="toc-text">迁移</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B0%E5%A2%9E"><span class="toc-number">1.0.4.</span> <span class="toc-text">新增</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%96%B0%E5%A2%9E%E4%B8%80%E6%9D%A1"><span class="toc-number">1.0.4.0.1.</span> <span class="toc-text">新增一条</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%96%B0%E5%A2%9E%E5%A4%9A%E6%9D%A1"><span class="toc-number">1.0.4.0.2.</span> <span class="toc-text">新增多条</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%9F%A5%E8%AF%A2%E4%B8%80%E6%9D%A1"><span class="toc-number">1.0.4.0.3.</span> <span class="toc-text">查询一条</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%97%B6%E9%97%B4%E7%9B%B8%E5%85%B3%E9%94%99%E8%AF%AF"><span class="toc-number">1.0.4.0.4.</span> <span class="toc-text">时间相关错误</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%9F%A5%E8%AF%A2%E6%89%80%E6%9C%89"><span class="toc-number">1.0.4.0.5.</span> <span class="toc-text">查询所有</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#distinct"><span class="toc-number">1.0.4.0.6.</span> <span class="toc-text">distinct</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%8A%95%E5%BD%B1"><span class="toc-number">1.0.4.0.7.</span> <span class="toc-text">投影</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#Limit%E5%92%8COffset"><span class="toc-number">1.0.4.0.8.</span> <span class="toc-text">Limit和Offset</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%9D%A1%E4%BB%B6%E6%9F%A5%E8%AF%A2"><span class="toc-number">1.0.4.0.9.</span> <span class="toc-text">条件查询</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%8E%92%E5%BA%8F"><span class="toc-number">1.0.4.0.10.</span> <span class="toc-text">排序</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%88%86%E7%BB%84"><span class="toc-number">1.0.4.0.11.</span> <span class="toc-text">分组</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#Join"><span class="toc-number">1.0.4.0.12.</span> <span class="toc-text">Join</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%9B%B4%E6%96%B0"><span class="toc-number">1.0.4.0.13.</span> <span class="toc-text">更新</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%88%A0%E9%99%A4"><span class="toc-number">1.0.4.0.14.</span> <span class="toc-text">删除</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="vue3左侧菜单隐藏某选项"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项">vue3左侧菜单隐藏某选项</a><time datetime="2023-07-29T06:32:00.000Z" title="发表于 2023-07-29 14:32:00">2023-07-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Vue状态管理"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理">Vue状态管理</a><time datetime="2023-07-13T09:29:00.000Z" title="发表于 2023-07-13 17:29:00">2023-07-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="基于IOC解决对象依赖问题"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题">基于IOC解决对象依赖问题</a><time datetime="2023-06-27T03:32:00.000Z" title="发表于 2023-06-27 11:32:00">2023-06-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Gin框架"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架">Gin框架</a><time datetime="2023-06-23T06:32:00.000Z" title="发表于 2023-06-23 14:32:00">2023-06-23</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="ServeMux、httprouter"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter">ServeMux、httprouter</a><time datetime="2023-06-04T03:32:00.000Z" title="发表于 2023-06-04 11:32:00">2023-06-04</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/dujie5416/img/longzhu.png')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2024  <i id="heartbeat" class="fa fas fa-heartbeat"></i> J.</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a><a href="http://beian.miit.gov.cn/"  style="color:#f72b07" target="_blank">京ICP备2022023567号</a></div></div><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/HCLonely/images@master/others/heartbeat.min.css"></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="search-wrap"><div id="algolia-search-input"></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-info"><div class="algolia-stats"></div><div class="algolia-poweredBy"></div></div></div></div></div><div id="search-mask"></div></div><div id="rightMenu"><div class="rightMenu-group rightMenu-small"><div class="rightMenu-item" id="menu-backward"><i class="fa-solid fa-arrow-left"></i></div><div class="rightMenu-item" id="menu-forward"><i class="fa-solid fa-arrow-right"></i></div><div class="rightMenu-item" id="menu-refresh"><i class="fa-solid fa-arrow-rotate-right"></i></div><div class="rightMenu-item" id="menu-home"><i class="fa-solid fa-house"></i></div></div><div class="rightMenu-group rightMenu-line rightMenuOther"><a class="rightMenu-item menu-link" href="/archives/"><i class="fa-solid fa-archive"></i><span>文章归档</span></a><a class="rightMenu-item menu-link" href="/categories/"><i class="fa-solid fa-folder-open"></i><span>文章分类</span></a><a class="rightMenu-item menu-link" href="/tags/"><i class="fa-solid fa-tags"></i><span>文章标签</span></a></div><div class="rightMenu-group rightMenu-line rightMenuNormal"><a class="rightMenu-item menu-link" id="menu-radompage" href="/random/index.html"><i class="fa-solid fa-shoe-prints"></i><span>随便逛逛</span></a><div class="rightMenu-item" id="menu-translate"><i class="fa-solid fa-earth-asia"></i><span>繁简切换</span></div><div class="rightMenu-item" id="menu-darkmode"><i class="fa-solid fa-moon"></i><span>切换模式</span></div></div></div><div id="rightmenu-mask"></div><div><script src="/dujie5416/js/utils.js"></script><script src="/dujie5416/js/main.js"></script><script src="/dujie5416/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/algoliasearch/dist/algoliasearch-lite.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instantsearch.js/dist/instantsearch.production.min.js"></script><script src="/dujie5416/js/search/algolia.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>function loadLivere () {
  if (typeof LivereTower === 'object') {
    window.LivereTower.init()
  }
  else {
    (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
    })(document, 'script');
  }
}

if ('Livere' === 'Livere' || !false) {
  if (false) btf.loadComment(document.getElementById('lv-container'), loadLivere)
  else loadLivere()
}
else {
  function loadOtherComment () {
    loadLivere()
  }
}</script></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script data-pjax defer src="https://npm.elemecdn.com/tzy-blog/lib/js/theme/chocolate.js"></script><canvas id="universe"></canvas><script defer src="/js/universe.js"></script><script defer data-pjax src="/js/rightMenu.js"></script><div class="aplayer no-destroy" data-id="7427714271" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-lrctype="1" data-preload="none" data-autoplay="true" muted></div><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-show-text.min.js" data-mobile="false" data-text="I,LOVE,YOU" data-fontsize="15px" data-random="false" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["meta[property=\"og:image\"]","meta[property=\"og:title\"]","meta[property=\"og:url\"]","head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>
  function butterfly_clock_anzhiyu_injector_config(){
    var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
    var item_html = '<div class="card-widget card-clock"><div class="card-glass"><div class="card-background"><div class="card-content"><div id="hexo_electric_clock"><img class="entered loading" id="card-clock-loading" src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/loading.gif" style="height: 120px; width: 100%;" data-ll-status="loading"/></div></div></div></div></div>';
    console.log('已挂载butterfly_clock_anzhiyu')
    if(parent_div_git) {
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var qweather_key = '56289903f0d448dfbe8262dba0175f70';
  var gaud_map_key = '01603f2b2d08d0e947bb101e9d9b148b';
  var baidu_ak_key = 'undefined';
  var flag = 0;
  var clock_rectangle = '112.982279,28.19409';
  var clock_default_rectangle_enable = 'false';

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_clock_anzhiyu_injector_config();
  }
  else if (epage === cpage){
    butterfly_clock_anzhiyu_injector_config();
  }
  </script><script src="https://widget.qweather.net/simple/static/js/he-simple-common.js?v=2.0"></script><script data-pjax src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.js"></script><!-- hexo injector body_end end --><script src="/dujie5416/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"tagMode":false,"debug":false,"model":{"jsonPath":"/dujie5416/live2dw/assets/tororo.model.json"},"display":{"position":"right","width":150,"height":350,"hOffset":20,"vOffset":-20},"mobile":{"show":false},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/"});</script><script async>window.onload=function(){var a=document.createElement('script'),b=document.getElementsByTagName('script')[0];a.type='text/javascript',a.async=!0,a.src='/sw-register.js?v='+Date.now(),b.parentNode.insertBefore(a,b)};</script></body></html>